package cn.gov.pbc.tims.interceptor;

import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.gov.pbc.tims.entity.User;
import cn.gov.pbc.tims.util.Operator;

public class SystemSessionInterceptor implements HandlerInterceptor {  
    private static final String LOGIN_URL="/index.jsp";  
    @Autowired
	private Operator operator;
    @Override  
    public void postHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler,  
            ModelAndView modelAndView) throws Exception {  
          
  
    }  
  
    @Override  
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex)  
            throws Exception {  
  
    }  
  
    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,  
            Object handler) throws Exception {  
    	  HttpSession session=request.getSession(true);  
          //session中获取用户名信息  
          Object obj = session.getAttribute("op");
          //如果沒有登陸則檢查cookie,從cookie中取用戶名和密碼，自動登陸。
          if (!operator.isLogin()) {  
              Cookie[] cookies = request.getCookies();  
              if(null!=cookies){    
              	 String   usernameCookie="";
              	 String   pwdCookie="";
              	 for(Cookie cookie : cookies){    
                          if("username".equals(cookie.getName())){  
                        	  usernameCookie = URLDecoder.decode(cookie.getValue(),"utf-8");
                          }else if("pwd".equals(cookie.getName())){  
                        	  pwdCookie =URLDecoder.decode(cookie.getValue(),"utf-8");
                          }  
                  }    
                  if(!"".equals(usernameCookie) && !"".equals(pwdCookie)){  
                	  //2018-09-15登陸處理，如果用戶名密碼匹配成功則登陸成功，否則登陸失敗。
                	 // System.out.println("name:"+usernameCookie+"  password:"+pwdCookie);
                     User op=  operator.authenticate(usernameCookie, pwdCookie);
                  } 
                }
              }
              
              if (!operator.isLogin()) {    
	              response.sendRedirect(request.getSession().getServletContext().getContextPath()+LOGIN_URL);
	              //System.out.println(request.getSession().getServletContext().getContextPath()+LOGIN_URL);  
	              return false;
                }
    	
    	
    	
           return true;
     }
}